from datetime import datetime
import requests



# API的基础URL
base_url = 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/6499516269/platforms/ios/reviews'

# 请求头相关参数
headers = {
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'zh-CN,zh;q=0.9',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        # 添加其他必要的请求头，如认证信息
        'Cookie':'s_fid=722C4D05C185690C-0452A3CBE40FEA72; s_vi=[CS]v1|33C44E1C90E6D42F-6000197F41C07960[CE]; XID=727baf56bc1d46e0386d36e689760e2c; geo=KR; s_cc=true; dslang=CN-ZH; site=CHN; myacinfo=DAWTKNV323952cf8084a204fb20ab2508441a07d02d3e6963dcad3e78babe59a8b761686f0ec67d495e00ca1ea7afb5852b75a9ad29dc4afd0085f62d1c316ce984c16875aa6be33fd0d367e7404b29962c2cea6f62eb5719762c25c7cfdd750ad6b4dd97dc584eecc60812d7e9b61b8c6c0b43ccb5dae5f1fa970f297bdb9bbfde3cf138918b5463764bb6374595f713a62fda8a52e6ddd78a3d70e234e7fecd0f5000911745b1196ea3e9c8a5ebfa16c9b3474b8eefd549bd4ceee5f4c7beb18ba642465d9a5da1c820ded37a02fcc62c0c60a858e813a2c1c153c503f619ed6d17fd889ca9ada3a5f30e50a87030ad0d245afa27c67e9f0d06b75920cf9928d78f52a62ef5db10c0a29ec2c8f097d3425b6c6e118aebcd2d8200e449ad0c7d802a71495a35f828a1f041c4efbccc4fd02eca84772fbb3725d5b34a46f8490302f6efa01d4627c436c7362e80a4d5cb12812672d15aeaeec8f84bce906121c9292a7f44e7dedcd1fa95fda6160186ea5dcc44a948e1eb4712c71175cf4a8b002731e1c0b89200876743b9a00f7900204cf70d994c8190cd48c4bd0481cb2814221928450bdfe827dd0aa831960c44e5dd6995871e44a8ab144d9e85d80d8277240ce76a260421e3e4c96291d67bf08bd5372736d81d5aceaf504e1ba7685c1a167a782955d372ce1ea733b20dddee944a3abfc1870f282f26ee5b5e5beba413b2f1f340f65f2be009906a8ae23fb0bbf27f3302f3a237da1a72b81c8220d1bc95f828b89a18aad243b6abca15eb3af7ff9360c92673515ce30c496742451eaf40bd85f3e280b9792bb798e7b5697d3c1e5911ae1584a5785e35f033c348281029167ca50dea34c5877910c8fc20f68fd0c0278ad8bcd2f2ce60299c5379c6da156d5e6bb70d5aa07e76d0ce9905ad82ff29f7ba822dddfb514566b21dce273c290bd374629771a07a22788e19a1a8c19a48e1bb23a5662273a2770dd4e3036cb805c6cffbc585a47V3; dc=pv; itctx=eyJjcCI6ImM2NjM4Y2I2LTdiNWYtNGFiYy05MjQ0LWJjMjUzYTI0Zjc0OSIsImRzIjoxODE0NTg4ODg2OCwiZXgiOiIyMDI1LTEtMTcgMTA6MToxMSJ9|2s6hscpael7mf62f3tgh7a4ccs|ePljP8giDV-hcCFKe-1l7JgLc_U; itcdq=0; dqsid=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MzcwOTg5NTMsImp0aSI6IlluX3VCQWgxdmxncXhpb0MtNkxjYlEifQ.kidlSZtlJnZQ4oT9KENUiNpsmw8VrCYGwDe_6uJ1mCQ; wosid=r95kdXyenS7w4OssU8dk0M; woinst=9315; s_sq=applesuperglobal%3D%2526pid%253DActivity%252520-%252520Ratings%252520Responses%2526pidt%253D1%2526oid%253Dhttps%25253A%25252F%25252Fappstoreconnect.apple.com%25252FWebObjects%25252FiTunesConnect.woa%25252Fra%25252Fng%25252F%2526ot%253DA'

}

def fetch_reviews(start_time,end_time):

    # 定义时间格式
    datetime_format = '%Y-%m-%d %H:%M:%S'

    # 将字符串时间转换为datetime对象
    start_time = datetime.strptime(start_time, datetime_format)
    end_time = datetime.strptime(end_time, datetime_format)

    #将date_time 转为 time_stamp
    start_stamp = int(start_time.timestamp() * 1000)
    end_stamp = int(end_time.timestamp() * 1000)

    # 评分等级
    rating_list = ['RATING_1', 'RATING_2', 'RATING_3', 'RATING_4', 'RATING_5']
    # rating_list = ['RATING_1', 'RATING_2']
    #分页
    index_list1 = [0, 100, 200, 300]
    index_list2 = [0, 100, 200, 300,400,500,600,700,800,900]
    # index_list = [0,100]

    # 初始化计数器
    rating_counts = {i: 0 for i in range(1, 6)}

    for rating in rating_list:

        # 如果是5星，则分页多一点，因为五星好评平均每天在150左右
        if rating == 'RATING_5':
            current_index_list = index_list2
        else:
            current_index_list = index_list1
        for index in current_index_list:
            # 请求体相关参数
            params = {
                'rating': rating,  # 评分
                'storefront': 'US',
                'sort': 'REVIEW_SORT_ORDER_MOST_RECENT',
                'index': index,  # 分页
            }
            # 发送请求&拿到res
            response = requests.get(url = base_url, params=params,headers = headers)
            if response.status_code == 200:

                reviews = response.json().get('data', {}).get('reviews', [])  # 获取评论列表
                appVersionString = reviews[0].get('value').get('appVersionString')  # 获取版本号
                for review in reviews:  # 遍历评论列表
                    timestamp = review.get('value').get('lastModified')  # 获取评论时间戳
                    ratings = review.get('value').get('rating')  # 获取评分
                    if timestamp and ratings and start_stamp <= timestamp <= end_stamp and 1 <= ratings <= 5:  # 判断时间戳是否在指定范围内，评分是否在1-5之间
                        rating_counts[ratings] += 1
            else:
                print(f"ERROR，CODE: {response.status_code}，rating: {rating}, index: {index}")


    return rating_counts,appVersionString

def fetch_total_reviews(rating_counts,appVersionString):

    print("iOS - Haven商店评价统计及回复 （1.13 + 1.14 + 1.15）：")
    print("  - 差评1星：{}条；版本{}".format(rating_counts.get(1, 0),appVersionString))
    print("  - 差评2星：{}条；版本{}".format(rating_counts.get(2, 0),appVersionString))
    print("  - 中评3星：{}条；版本{}".format(rating_counts.get(3, 0),appVersionString))
    print("  - 好评4星：{}条；版本{}".format(rating_counts.get(4, 0),appVersionString))
    print("  - 好评5星：{}条；版本{}".format(rating_counts.get(5, 0),appVersionString))



if __name__ == '__main__':
    start_time_str = '2025-01-13 00:00:00'
    end_time_str = '2025-01-15 23:59:59'

    # fetch_reviews(start_time_str, end_time_str)
    fetch_total_reviews(*fetch_reviews(start_time_str, end_time_str))
